package com.xb.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xb.model.domain.dto.PageDTO;
import com.xb.model.domain.vo.CompletedFileVO;
import com.xb.model.domain.vo.ErrorFileVO;
import com.xb.model.domain.vo.PendingFileVO;
import com.xb.model.domain.entity.FileUpload;
import com.xb.system.mapper.db1.FileUploadMapper;
import com.xb.system.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class FileUploadServiceImpl extends ServiceImpl<FileUploadMapper, FileUpload> implements FileUploadService {

    @Override
    public IPage<PendingFileVO> getPendingFiles(Long userId, PageDTO pageDTO) {
        Page<FileUpload> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        LambdaQueryWrapper<FileUpload> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileUpload::getUserId, userId)
                .eq(FileUpload::getStatus, "未完成")
                .eq(FileUpload::getIsDeleted, 0)
                .orderByDesc(FileUpload::getUploadTime);

        IPage<FileUpload> filePage = page(page, queryWrapper);
        long total = count(queryWrapper);
        filePage.setTotal(total);
        return filePage.convert(file -> {
            PendingFileVO vo = new PendingFileVO();
            vo.setId(file.getId());
            vo.setFileName(file.getFileName());
            vo.setUploadTime(file.getUploadTime());
            return vo;
        });
    }

    @Override
    public IPage<CompletedFileVO> getCompletedFiles(Long userId, PageDTO pageDTO) {
        // 确保分页参数有效
        if (pageDTO.getPageNum() < 1 || pageDTO.getPageSize() < 1) {
            throw new IllegalArgumentException("分页参数无效：pageNum 和 pageSize 必须大于 0");
        }

        // 创建分页对象
        Page<FileUpload> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<FileUpload> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileUpload::getUserId, userId)
                .eq(FileUpload::getStatus, "已完成")
                .eq(FileUpload::getIsDeleted, 0)
                .orderByDesc(FileUpload::getUploadTime);

        // 执行分页查询
        IPage<FileUpload> filePage = page(page, queryWrapper);

        // 转换数据
        IPage<CompletedFileVO> resultPage = filePage.convert(file -> {
            CompletedFileVO vo = new CompletedFileVO();
            vo.setId(file.getId());
            vo.setFileName(file.getFileName());
            vo.setTotalCount(file.getTotalCount());
            return vo;
        });

        log.info("分页结果 - Total: {}, Current: {}, Size: {}, Records: {}",
                resultPage.getTotal(), resultPage.getCurrent(), resultPage.getSize(), resultPage.getRecords().size());

        return resultPage;
    }

    @Override
    public IPage<ErrorFileVO> getErrorFiles(Long userId, PageDTO pageDTO) {
        Page<FileUpload> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        LambdaQueryWrapper<FileUpload> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileUpload::getUserId, userId)
                .eq(FileUpload::getStatus, "格式错误") // 数据库中的 "格式错误" 状态对应前端的 "格式错误" 标签页
                .eq(FileUpload::getIsDeleted, 0)
                .orderByDesc(FileUpload::getUploadTime);

        IPage<FileUpload> filePage = page(page, queryWrapper);
        long total = count(queryWrapper);
        filePage.setTotal(total);
        return filePage.convert(file -> {
            ErrorFileVO vo = new ErrorFileVO();
            vo.setId(file.getId());
            vo.setFileName(file.getFileName());
            vo.setUploadTime(file.getUploadTime());
            vo.setErrorMsg(file.getErrorMessage());
            return vo;
        });
    }

    @Override
    public void deleteFile(Long fileId) {
        FileUpload file = getById(fileId);
        if (file != null) {
            file.setIsDeleted(1);
            updateById(file);
        } else {
            throw new RuntimeException("文件未找到。");
        }
    }
}